package cn.tudu.boot21.controller;

import cn.tudu.boot21.entity.User;
import cn.tudu.boot21.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

@Controller
public class UserController {
  @RequestMapping("/reg")
  @ResponseBody
    public String reg(User user){
      try(
              Connection conn = DBUtils.getConn();

              ) {
          String sql = "select id from user where username=?";
          PreparedStatement ps = conn.prepareStatement(sql);
          ps.setString(1, user.getUsername());
          ResultSet rs = ps.executeQuery();
          if(rs.next()){
             return "用户名存在";

          }
              String sql1 = "insert into user values(null,?,?,?)";
              PreparedStatement insertPs = conn.prepareStatement(sql1);
              insertPs.setString(1, user.getUsername());
              insertPs.setString(2, user.getPassword());
              insertPs.setString(3, user.getNickname());
              insertPs.executeUpdate();
              return "注册成功";


      } catch (SQLException throwables) {
          throwables.printStackTrace();
      }
      return user.toString();
  }
  @RequestMapping("/login")
  @ResponseBody
  public String login(User user){
      //soutp

      try (
              Connection conn = DBUtils.getConn();
      ){
          String sql = "select password from user where username=?";
          PreparedStatement ps = conn.prepareStatement(sql);
          ps.setString(1,user.getUsername());
          ResultSet rs = ps.executeQuery();
          if(rs.next()){
              //得到查询密码
              String pw = rs.getString(1);
              if(pw.equals(user.getPassword())){
                  return "登录成功";
              }
                  return "密码错误";
          }
      } catch (SQLException throwables) {
          throwables.printStackTrace();
      }
        return "用户名不存在";
  }
}
